package ar.com.fiuba.ElectronicCircuitAnalyst.domain.impl.functions.jeval;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JevalFunctionStringProcessor {

	private static final String OR = "or";
	private static final String AND = "and";
	private static final String XOR = "xor";
	private static final String NOT = "not";
	private static final String OR_SYMBOL = "||";
	private static final String AND_SYMBOL = "&&";
	private static final String XOR_SYMBOL = "^";
	private static final String NOT_SYMBOL = "!";
	
	private static final String PATTERN_STR = "(E[\\d]+)";
	private static final String REPLACE_STR = "#{$1}";
	
	private Pattern pattern = Pattern.compile(PATTERN_STR);
	
	/**
	 * Process the given string so it can be evaluated with JEval
	 * If input is: "E1 and E3 or not E4"
	 * The result is: "#{E1} && #{E3} || ! #{E4}"
	 * 
	 * @param functionString the string to process
	 * @return the processed string
	 */
	public String process(String functionString){
		return this.replaceVariableNames(this.replaceOperands(functionString));
	}
	
	private String replaceOperands(String functionString){
		return ((((functionString)
				.replaceAll(AND, AND_SYMBOL))
				.replaceAll(XOR, XOR_SYMBOL))
				.replaceAll(OR, OR_SYMBOL))
				.replaceAll(NOT, NOT_SYMBOL);
	}
	
	/**
	 * Replaces all occurrences of variable names with Jeval variable names.
	 * "E1 and E10" --> "#{E1} and #{E10}"
	 */
	private String replaceVariableNames(String functionString){
		Matcher matcher = pattern.matcher(functionString);
		return matcher.replaceAll(REPLACE_STR);
	}
}
